<?php
// +----------------------------------------------------------------------
// | Author: Stupboy King
// +----------------------------------------------------------------------
namespace app\api\exception;

use app\base\service\Ding;
use app\base\service\Mail;
use think\Config;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\DbException;

class Http extends Handle
{

    public function render(\Exception $e)
    {
        if ($e instanceof HttpException) {
            $statusCode = $e->getStatusCode();
        }

        if (!isset($statusCode)) {
            $statusCode = 0;
        }

        $msg = $e->getMessage();

        // 自定义的错误消息
        if($e instanceof \app\base\exception\BaseException){
            $msg = $e->msg;
            $statusCode = $e->errorCode;
        }

        if($e instanceof BaseException){
            $statusCode = $e->errorCode;
        }

        // 如果已经定义有错误消息，使用定义好的错误消息
        if(!$msg){
            $codeKey = strval($statusCode);
            Config::set(include APP_PATH . '/../config/api/config.php', 'api');
            $errMsgArr = Config::get('api.error_msg');
            $msg = isset($errMsgArr[$codeKey]) ? $errMsgArr[$codeKey] : $msg;
        }

        // 数据库异常，发送邮件通知
        if($e instanceof DbException) {
            $msg .= ',请求地址:'.$_SERVER["REQUEST_URI"].$e->getTraceAsString();
            Mail::markDebug('API错误记录:', $msg );
            (new Ding())->send($msg);
            // 非调试模式下重写错误消息
            if(!Config::get('app_debug')) {
                $msg = '系统错误';
            }
        }

        $result  = [
            'code' => $statusCode,
            'msg'  => $msg,
            'time' => $_SERVER['REQUEST_TIME']
        ];
        header("Access-Control-Allow-Origin: * ");
        header("Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: content-type,user-token");
        header("Access-Control-Max-Age: 2592000");
        return json($result, 200);
    }
}